package com.hongshan.wallet.base

import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.view.View
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.transition.Transition

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.hongshan.wallet.base
 * @author   : zhangxx
 * @date     : 2019/5/23
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class BaseViewTarget<T : View>(view: T) : CustomViewTarget<T, Drawable>(view), Transition.ViewAdapter {

    private var animatable: Animatable? = null

    override fun onLoadFailed(errorDrawable: Drawable?) {
        view.setBackground(errorDrawable)
    }

    override fun onResourceCleared(placeholder: Drawable?) {
        view.setBackground(placeholder)
    }

    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
        if (transition == null || !transition.transition(resource, this)) {
            view.setBackground(resource)
//            setResourceInternal(resource)
        }
        maybeUpdateAnimatable(resource)
    }

    override fun getCurrentDrawable(): Drawable? {
        return null
    }

    override fun setDrawable(drawable: Drawable?) {

    }

    private fun maybeUpdateAnimatable(resource: Drawable?) {
        if (resource is Animatable) {
            animatable = resource
            animatable?.start()
        } else {
            animatable = null
        }
    }

    override fun onStart() {
        super.onStart()
        animatable?.start()
    }

    override fun onStop() {
        super.onStop()
        animatable?.stop()
    }
}